﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace Zyg.SSO.Core
{
    /// <summary>
    /// 验证票据
    /// </summary>
    [Serializable()]
    public class Ticket
    {
        #region Fields and Properties

        private string userId = string.Empty;
        /// <summary>
        /// 用户标识
        /// </summary>
        public string UserId { get { return userId; } set { userId = value; } }

        private string appId = string.Empty;
        /// <summary>
        /// 应用标识
        /// </summary>
        public string AppId { get { return this.appId; } set { appId = value; } }

        private string ip = string.Empty;
        /// <summary>
        /// 用户请求的IP
        /// </summary>
        public string IP { get { return ip; } set { ip = value; } }

        private DateTime createdTime = DateTime.MinValue;
        /// <summary>
        /// 票据生成时间
        /// </summary>
        public DateTime CreatedTime { get { return createdTime; } set { createdTime = value; } }

        #endregion

        #region Static Methods

        public static string Serialize(Ticket ticket)
        {
            MemoryStream stream = new MemoryStream();

            IFormatter formatter = new BinaryFormatter();

            formatter.Serialize(stream, ticket);

            byte[] buffer = stream.ToArray();

            return Convert.ToBase64String(buffer);
        }

        public static Ticket DeSerialize(string serializedString)
        {
            try
            {
                byte[] buffer = Convert.FromBase64String(serializedString);

                MemoryStream stream = new MemoryStream(buffer);

                IFormatter formatter = new BinaryFormatter();

                Ticket ticket = formatter.Deserialize(stream) as Ticket;
                return ticket;
            }
            catch
            {
                throw new Exception("票据转化失败");
            }
        }

        #endregion
    }
}
